﻿using HCMS.CommonDtos;
using HCMS.Entities.Manage;
using HCMS.IRepositories.Manage;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp.EntityFrameworkCore;

namespace HCMS.Repositories.Manage
{
    /// <summary>
    /// 管理 菜单
    /// </summary>
    public class MenuRepository : ManageBaseRepository<Menu>, IMenuRepository
    {
        public MenuRepository(IDbContextProvider<ManageDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }

        /// <summary>
        /// 管理 列表
        /// </summary>
        /// <param name="searchArgs">搜索 参数</param>
        /// <param name="pager">分页 参数</param>
        /// <returns></returns>
        public async Task<ListPagerDto<Menu>> ManageList(SearchArgsDto searchArgs, PagerArgsDto pager)
        {
            var query = await GetQueryableAsync();

            if (!string.IsNullOrWhiteSpace(searchArgs.SearchName) && !string.IsNullOrWhiteSpace(searchArgs.SearchKey))
            {
                switch (searchArgs.SearchName)
                {
                    case "name":
                        query = query.Where(t => t.Name.Contains(searchArgs.SearchKey));
                        break;
                }
            }

            if (searchArgs.Status != 9999)
            {
                query = query.Where(t => t.Status == searchArgs.Status);
            }

            var count = await query.CountAsync();
            pager.RowCount = count;

            var list = new List<Menu>();

            if (count > 0)
            {
                query = query.OrderByDescending(t => t.Id);

                list = await query
                           .Skip((pager.CurrentPageIndex - 1) * pager.PageSize)
                           .Take(pager.PageSize)
                           .ToListAsync();
            }

            var result = new ListPagerDto<Menu>()
            {
                Data = list ?? new List<Menu>(),
                PagerInfo = pager
            };

            return result;
        }

        /// <summary>
        /// 菜单 树
        /// </summary>
        /// <param name="status">状态</param>
        /// <returns></returns>
        public async Task<object> GetAllTree(int status = 9999)
        {
            var query = await GetQueryableAsync();
            var all = await query.ToListAsync();

            all.Add(new Menu()
            {
                Name = "根节点",
                ParentId = -1
            });

            // 递归 构建树
            Func<int, bool, object> funcTree = null;
            funcTree = delegate (int parentId, bool isRoot)
            {
                Func<Menu, bool> where = (a => a.Id == 0 && a.ParentId == -1);
                if (!isRoot)
                {
                    if (status != 9999)
                    {
                        where = (a => a.ParentId == parentId && a.Status == status);
                    }
                    else
                    {
                        where = (a => a.ParentId == parentId);
                    }
                }

                var obj = all.Where(where).OrderByDescending(a => a.Orders).Select(a => new
                {
                    id = a.Id,
                    name = a.Name,
                    status = a.Status,
                    createTime = a.CreateTime,
                    createUser = a.CreateUser,
                    updateTime = a.UpdateTime,
                    updateUser = a.UpdateUser,
                    icon = a.Icon,
                    typeId = a.TypeId,
                    children = funcTree(a.Id, false)
                }).ToList();

                return obj;
            };

            return funcTree(0, true);
        }

        /// <summary>
        /// 获取管理系统 菜单树
        /// </summary>
        /// <param name="menuIds">已选中菜单 Ids</param>
        /// <returns></returns>
        public async Task<List<ManageMenuTreeDto>> GetManageMenuTree(List<int> menuIds)
        {
            if (menuIds == null || menuIds.Count == 0)
            {
                return new List<ManageMenuTreeDto>();
            }

            var query = await GetQueryableAsync();
            var all = await query.ToListAsync();

            // 菜单不包含【权限按钮】
            all = all.Where(t => t.TypeId != 3 && t.Status == 0 && menuIds.Contains(t.Id))?.ToList();
            if (all == null)
            {
                return new List<ManageMenuTreeDto>();
            }

            // 递归 构建树
            Func<int, bool, List<ManageMenuTreeDto>> funcTree = null;
            funcTree = delegate (int parentId, bool isRoot)
            {
                Func<Menu, bool> where = (a => a.Id == 0 && a.ParentId == -1);
                if (!isRoot)
                {
                    where = (a => a.ParentId == parentId);
                }

                var list = all.Where(where)?.OrderByDescending(a => a.Orders)?.ToList();
                list = list ?? new List<Menu>();

                var result = new List<ManageMenuTreeDto>();
                foreach (var item in list)
                {
                    // 子级有【列表】模块，就构建 菜单链接信息
                    var listIndex = all.Where(a => a.TypeId == 2 && a.ParentId == item.Id)?.ToList();
                    if (listIndex != null && listIndex.Count > 0)
                    {
                        result.Add(new ManageMenuTreeDto()
                        {
                            Id = listIndex[0].Id,
                            Title = item.DisplayName,
                            Icon = item.Icon,
                            Type = 1,
                            OpenType = "_iframe",
                            Href = $"/{listIndex[0].ControllerName}/{listIndex[0].ActionName}/".ToLower()
                        });
                    }
                    else
                    {
                        result.Add(new ManageMenuTreeDto()
                        {
                            Id = item.Id,
                            Title = item.DisplayName,
                            Icon = item.Icon,
                            Type = 0,
                            Children = funcTree(item.Id, false)
                        });
                    }
                }

                return result;
            };

            return funcTree(0, false);
        }

        /// <summary>
        /// 根据 菜单 Id 获取关联的菜单列表
        /// </summary>
        /// <param name="menuIds">菜单 Id</param>
        /// <returns></returns>
        public async Task<List<Menu>> GetMenuListByIds(List<int> menuIds)
        {
            var result = new List<Menu>();

            var query = await GetQueryableAsync();
            var all = await query.ToListAsync();

            foreach (var menuId in menuIds)
            {
                var menu = all.FirstOrDefault(t => t.Id == menuId);
                if (menu != null)
                {
                    result.Add(menu);

                    if (!string.IsNullOrWhiteSpace(menu.ParentPath))
                    {
                        var parentPathArray = menu.ParentPath.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        var parentPathIdList = Array.ConvertAll(parentPathArray, int.Parse).ToList();

                        var parentList = all.Where(t => parentPathIdList.Contains(t.Id))?.ToList();
                        if (parentList != null && parentList.Any())
                        {
                            result.AddRange(parentList);
                        }
                    }
                }
            }

            // 去除重复的父级菜单
            result = result.Distinct().ToList();

            return result;
        }

    }
}
